package com.example.demo.test;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName Strdent
 * @Description
 * @date 2022/12/19 9:53
 * @Author yanceysong
 * @Version 1.0
 */
public class Student extends Person {
    private String career;

    public Student(String name, int age, String career) {
        super(name, age);
        this.career = career;
    }

    /**
     * 获取连接池的key
     *
     * @param ip      ip
     * @param db_name name
     * @return 连接池的key
     */
    private static String getKey(String ip, String db_name) {
        return "jdbc:sqlserver://" + ip + ";DatabaseName=" + db_name;
    }

    public static void main(String[] args) throws Exception {
        try {
            Connection connection = DriverManager.getConnection(getKey("172.21.1.94", "ORAPS_SCSS_BS_2.0_Hanjie_2"), "sa", "Oraps123");
            ScriptRunner scriptRunner = new ScriptRunner(connection);
            Resources.setCharset(StandardCharsets.UTF_8); //设置字符集,不然中文乱码插入错误
            scriptRunner.setLogWriter(null);//设置是否输出日志
            StringReader stringReader = new StringReader("C:\\Users\\BG264\\Desktop\\123.sql");
            scriptRunner.runScript(stringReader);
            scriptRunner.closeConnection();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<String> loadSql(String sqlFile) throws Exception {
        List<String> sqlList = new ArrayList<String>();

        try {
            InputStream sqlFileIn = new FileInputStream(sqlFile);

            StringBuffer sqlSb = new StringBuffer();
            byte[] buff = new byte[1024];
            int byteRead = 0;
            while ((byteRead = sqlFileIn.read(buff)) != -1) {
                sqlSb.append(new String(buff, 0, byteRead));
            }

            // Windows 下换行是 /r/n, Linux 下是 /n
            String[] sqlArr = sqlSb.toString().split("(;//s*//r//n)|(;//s*//n)");
            for (int i = 0; i < sqlArr.length; i++) {
                String sql = sqlArr[i].replaceAll("--.*", "").trim();
                if (!sql.equals("")) {
                    sqlList.add(sql);
                }
            }
            return sqlList;
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }

    @Override
    void info() {
        System.out.println("info run...");
    }
}
